package ru.urfc.portal.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import ru.urfc.portal.managers.AccountingManager;
import ru.urfc.portal.managers.ClientManager;
import ru.urfc.portal.model.accounting.UnifiedBalanceOperation;
import ru.urfc.portal.model.accounting.UnifiedBalanceOperationWithContragentName;
import ru.urfc.portal.ui.client.Constants;

@Stateless
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON})
@Path(Constants.CLIENTS +  "/{clientId}/" + Constants.BALANCE_OPERATIONS)
public class BalanceService extends BaseService {

	@EJB AccountingManager accountingManager;
	@EJB ClientManager clientManager;
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@GET
	public List<UnifiedBalanceOperation> listOperations(@PathParam("clientId") Long clientId,
			@Context HttpServletRequest request) {
		return accountingManager.getBalanceOperations(clientId, 
				getDate(FILTER_FROM_DATE, request), getDate(FILTER_TO_DATE, request));
	}

	@GET
	@Path(LAST_BALANCE_OPERATION)
	public UnifiedBalanceOperation lastOperation(@PathParam("clientId") Long clientId) {
		final String clientName = clientManager.getContragent(clientId).getName();
		try {
			UnifiedBalanceOperation balanceOperation = new UnifiedBalanceOperationWithContragentName(
					accountingManager.getBalanceAt(clientId, new Date()),
					clientName);
			balanceOperation.setBalance(balanceOperation.getAmountWithSign());
			return balanceOperation;
		} catch (Exception e) {
			logger.error("Returning fake balance because of exception: ", e);
			final UnifiedBalanceOperation balanceOperation2 = new UnifiedBalanceOperation();
			final UnifiedBalanceOperationWithContragentName balanceOperation = new UnifiedBalanceOperationWithContragentName(
					balanceOperation2, clientName);
			balanceOperation.setBalance(new BigDecimal(1023));
			return balanceOperation;
		}
	}
	
}
